#include "tcpclient.h"
#include <QDebug>
#include <QAbstractSocket>
#include <QNetworkProxy>
#include "log.h"
#include <QString>

TCPClient::TCPClient(QObject *parent) : QObject(parent)
{
    tcpSocket = new QTcpSocket(this);
    tcpSocket->setProxy(QNetworkProxy::NoProxy);

    connect(tcpSocket, &QTcpSocket::connected, [=]() {
        m_logger->writefile("TCP客户端连接成功");
        connect(tcpSocket, &QTcpSocket::readyRead, this, &TCPClient::onReadyRead);
    });
    connect(tcpSocket, &QTcpSocket::disconnected, [=]() {
        qDebug() << "[Client] Disconnected from server.";
    });
}

void TCPClient::connectToServer(const QString& host, int port, int key)
{
    clientKey = key;
    qDebug() << host << port;
    tcpSocket->connectToHost(host, port);
}

void TCPClient::onReadyRead()
{
    QByteArray data = tcpSocket->readAll();
    m_logger->writefile(QString("收到数据:%1").arg(QString::fromUtf8(data)));
    emit serverDataReceived(clientKey, data);
}

void TCPClient::onSocketError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    qDebug() << "[Client" << clientKey << "] Socket error:" << tcpSocket->errorString();
}


TCPClientManager::TCPClientManager(QObject *parent) : QObject(parent)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "my_connection");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("serialport");
    db.setUserName("root");
    db.setPassword("123456");

    if (!db.open()) {
        qDebug() << "数据库打开失败:" << db.lastError().text();
        return;
    }

    QMap<int,QVector<QVariant>>datasql=readDatabase(db);

    for(auto it=datasql.begin();it!=datasql.end();it++)
    {

        if(it.value().at(4)=="2")//数据库
        {
            this->setupTcpClient(it.key(),it.value());
        }
    }
}

QMap<int, QVector<QVariant> > TCPClientManager::readDatabase(QSqlDatabase& db)
{
    QMap<int, QVector<QVariant>> dataContainer;
    QSqlQuery query(db); // 关联已打开的数据库连接

    // 用于存储最终的 SQL 查询语句
    QString sqlQuery;

    // 构建查询 port 表的 SQL 语句
    sqlQuery = "select * FROM port WHERE protocol = '2'";

    // 准备 SQL 查询语句，如果准备失败，输出错误信息并返回空容器
    if (!query.prepare(sqlQuery))
    {
        qDebug() << "Query preparation failed:" << query.lastError().text();
        return dataContainer;
    }

    // 执行 SQL 查询语句，如果执行失败，输出错误信息并返回空容器
    if (!query.exec())
    {
        qDebug() << "Query execution failed:" << query.lastError().text();
        return dataContainer;
    }

    // 获取查询结果的记录信息，用于获取列名和列数
    QSqlRecord record = query.record();
    // 获取查询结果的列数
    int columnCount = record.count();
    int key=0;
    // 逐行遍历查询结果
    while (query.next())
    {
        // 用于存储当前行的数据
        QVector<QVariant> rowData;

        // 遍历当前行的每一列
        for (int i = 0; i < columnCount; ++i)
        {
            // 获取当前列的值
            QVariant value = query.value(i);
            // 将值添加到 rowData 中
            rowData.append(value);
        }

        // 将当前行的数据添加到 dataContainer 中
        dataContainer[key] = rowData;
        key++;
    }

    for(auto it=dataContainer.begin();it!=dataContainer.end();it++)
    {
        qDebug()<<it.value().at(0);
        qDebug()<<it.value().at(5);
    }

    // 返回存储查询结果的容器
    return dataContainer;
}

void TCPClientManager::setupTcpClient(int key, QVector<QVariant> Row)
{
    auto* client = new TCPClient(this);
    clients[key] = client;
    client->connectToServer(Row.at(5).toString(), Row.at(0).toInt(), key);
}
